/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evolve.webbot.portal;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import  com.gargoylesoftware.htmlunit.html.*;
import  java.text.SimpleDateFormat;

import java.util.Properties;
import java.util.Date;
import java.text.SimpleDateFormat;
import  java.util.logging.Level;
import  java.util.logging.Logger;
import  java.io.FileInputStream;
import  java.io.IOException;
import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.InputStream;
import  java.io.OutputStream;
import  javax.swing.JTextArea;
import  com.evolve.webbot.beans.WebBotBeans;
import  com.evolve.webbot.bean.SearsBean;
import  com.evolve.webbot.file.CommonErrorFile;
import  com.evolve.webbot.file.XmlFileSears;
import  org.jdom.Document;
import  org.jdom.Element;
import  org.jdom.JDOMException;
import  org.jdom.input.SAXBuilder;

/**
 *
 * @author DarthAE
 */
public class SearsInventarioInternacional 
{
   private String path;
   private JTextArea jtextArea;
   public static String WB_MAIN_DIR="evolve-webbot";
   public static String SEARS_MAIN_DIR="sears-webbot";
   public static String SEARS_PROP_DIR="sears-properties";
   public static String SEARS_PROP_ARC="SearsInventarioInternacionalPortal.properties";
   public static String SEARS_FILE_DIR="sears-files";
   public static String SEARS_ERROR_FILE="sears-error-";
   public static String SEARS_ARC_EXT =".zip";
   
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
   private SimpleDateFormat shf = new SimpleDateFormat("HHmmss");
   private SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
   private SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");
   
   static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger( SearsInventarioInternacional.class );   

   public SearsInventarioInternacional(){}
   
   public SearsInventarioInternacional(String path)
   {
       this.path = path;
   }

   public SearsInventarioInternacional(String path,JTextArea jtextArea)
   {
       this.path      = path;
       this.jtextArea = jtextArea;
   }

   public WebClient creaWebClient()
   {
       WebClient webClient = null;

       webClient = new WebClient();
       webClient.setJavaScriptEnabled(true);
       webClient.setThrowExceptionOnScriptError(false);
       webClient.setAjaxController(new NicelyResynchronizingAjaxController());

       try{
            webClient.setUseInsecureSSL(true);
          }catch(Exception e){System.out.println(e);}


       return webClient;
   }

   public WebClient accesoPortal(WebClient webClient)
   {
      int indPortalEjec       = 0;
      Date thisDate = new Date();
      String zipSearsFilePath = null;
      String xmlSearsFilePath = null;
      
      String errorFilePath ="";
      
      CommonErrorFile   cef = new CommonErrorFile();
      
      Properties properties = new Properties();
      
      errorFilePath = this.path+File.separator+WB_MAIN_DIR+
                                File.separator+SEARS_MAIN_DIR+
                                File.separator+SEARS_FILE_DIR+
                                File.separator+SEARS_ERROR_FILE+
                                sdf.format(thisDate)+"-"+
                                shf.format(thisDate)+".txt";
      
      this.jtextArea.append("\n[+]recuperando archivo sears inventario");

      try{           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+SEARS_MAIN_DIR+
                                                               File.separator+SEARS_PROP_DIR+
                                                               File.separator+SEARS_PROP_ARC);
           properties.load(fis);
           
           indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));

           if(indPortalEjec == 1)
           {              
               try{
                    HtmlPage          pg1 = (HtmlPage)webClient.getPage("http://proveedores.sears.com.mx/lib/login.asp");
                    HtmlForm          fm1 = (HtmlForm)pg1.getFormByName("frmAcceso");
                    HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName("txtUsuarioBURN");
                    HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName("txtContrasenaBURN");

                    ti1.setValueAttribute(properties.getProperty("Portal.user"));
                    pw1.setValueAttribute(properties.getProperty("Portal.passwd"));

                    HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName("btnEntrar");
                    HtmlPage        pg2  = (HtmlPage)si1.click();

                    if(pg2!=null)
                    {
                      HtmlPage pg3 = (HtmlPage)webClient.getPage("http://proveedores.sears.com.mx/lib/CriteriosGerenaArchivo.asp?Path=GenFile");

                      if(pg3!=null)
                      {
                         HtmlForm      fm2 = (HtmlForm)pg3.getFormByName("frmCriterio");
                         HtmlRadioButtonInput rb0 =(HtmlRadioButtonInput)fm2.getRadioButtonsByName("optGenerar").get(1);
                         log.info(rb0.getTextContent());
                         rb0.setChecked(true);
                         
                         HtmlRadioButtonInput rb1 =(HtmlRadioButtonInput)fm2.getRadioButtonsByName("optArts").get(0);
                         rb1.setChecked(true);

                         HtmlButtonInput ib1 =(HtmlButtonInput)fm2.getInputByName("cmdGenerar");                     

                         try{
                              InputStream  is  = ib1.click().getWebResponse().getContentAsStream();

                              Date fileDate = new Date();

                              SimpleDateFormat dateFotmat = new SimpleDateFormat("ddMMyyyy");
                              SimpleDateFormat timeFotmat = new SimpleDateFormat("HHmmss");

                              zipSearsFilePath = this.path+File.separator+WB_MAIN_DIR+
                                                           File.separator+SEARS_MAIN_DIR+
                                                           File.separator+SEARS_FILE_DIR+
                                                           File.separator+properties.getProperty("Sears.ArchivoPortal")+"-"+
                                                           dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+SEARS_ARC_EXT;
                          
                              OutputStream out = new FileOutputStream(new File(zipSearsFilePath));

                              int read=0;
                              byte[] bytes = new byte[1024];

                              while((read = is.read(bytes))!= -1)
                              {out.write(bytes, 0, read);}

                              is.close();
                              out.flush();
                              out.close();

                              this.jtextArea.append("\narchivo generado");
                          
                              this.jtextArea.append("\ngeneracion de archivo de datos");
                          
                              try {
                                    XmlFileSears readXML = new XmlFileSears();
                                    xmlSearsFilePath     = readXML.unZipXmlFile(zipSearsFilePath);
                                    readXML.writeSearsInventarioDataFile(readXML.getSearsInventarioRecords(xmlSearsFilePath),xmlSearsFilePath,
                                                               sdf3.format(new Date()),2);
                                  }catch(Exception e){
                                                       log.error("error al recuperar datos");
                                                       this.jtextArea.append("\nerror al generar archivo de datos");
                                                     }
//                                  catch (JDOMException ex)
//                                  {
//                                    Logger.getLogger(XmlFileSears.class.getName()).log(Level.SEVERE, null, ex);
//                                  }
//                                  catch (IOException ex)
//                                  {
//                                    Logger.getLogger(XmlFileSears.class.getName()).log(Level.SEVERE, null, ex);
//                                  }
                          
                            }catch(IOException ioe){ 
                                                     cef.writeCommonWebTxtFile(errorFilePath,"no se ha podido generar el archivo de datos");
                                                     
                                                   }
                      }
                    }
                  }catch(Exception e){                                          
                                        cef.writeCommonWebTxtFile(errorFilePath,"error al ingresar al portal sears inventario");
                                     }
           }
           else
           if(indPortalEjec == 0)
           {
             log.info("[-]Portal Sears Inventario Desactivado");           
           }

         }catch(IOException ioe){System.out.println(ioe);
                                 cef.writeCommonWebTxtFile(errorFilePath,"error al ingresar al portal sears inventario");
                                }

      return webClient;
   }
   
   public void terminaWebClient(WebClient webClient)
   {
       if(webClient!=null)
       {webClient.closeAllWindows();}
   }
}

